package main

import (
	"os"
	"fmt"
	"io"
)

/**
复制文件
 */

func main()  {
	srcFile := "/toMid/0F_Chain/01_BChain0514/01_go/pro/萌猫.jpg"
	dstFile := "/home/daniel/tmp/萌猫3.jpg"


	//testCopy()
	testCopy2()
	copyFile(srcFile, dstFile)


}
func testCopy()  {
	srcFile := "/toMid/0F_Chain/01_BChain0514/01_go/pro/萌猫.jpg"
	dstFile := "/home/daniel/tmp/萌猫.jpg"

	//打开文件
	file1, err1 := os.Open(srcFile)
	file2, err2 := os.OpenFile(dstFile, os.O_CREATE|os.O_WRONLY, os.ModePerm)

	if err1 != nil {
		fmt.Println("err:", err1)
		return
	}

	if err2 != nil {
		fmt.Println("err:", err2)
		return
	}

	defer file1.Close()
	defer file2.Close()

	//读取数据
	bs := make([]byte,1024, 1024)
	//n := -1
	total := 0
	for {
		n, err := file1.Read(bs)

		if n == 0 || err == io.EOF {
			fmt.Println("copy结束")
			break
		} else if err != nil {
			fmt.Println("报错,err:", err.Error())
			break
		}

		//写出数据
		file2.Write(bs[:n])
		total += n
	}



	//关闭文件
	file1.Close()
	file2.Close()
}

/**
复制文件
 */
func copyFile(srcFile, destFile string) (int64, error) {

	file1,err1 := os.Open(srcFile)
	file2,err2 := os.OpenFile(destFile, os.O_CREATE|os.O_WRONLY, os.ModePerm)

	defer file1.Close()
	defer file2.Close()

	if err1 != nil {
		fmt.Println("err:", err1)
		return 0,nil
	}
	if err2 != nil {
		fmt.Println("err:", err2)
		return 0,nil
	}

	return io.Copy(file1, file2)

}

/*
复制目录
*/
func testCopyDist()  {

}

func testCopy2()  {
	srcFile := "/toMid/0F_Chain/01_BChain0514/01_go/pro/萌猫.jpg"
	dstFile := "/home/daniel/tmp/萌猫2.jpg"


	//打开文件
	file1, err1 := os.Open(srcFile)
	file2, err2 := os.OpenFile(dstFile, os.O_CREATE|os.O_WRONLY, os.ModePerm)

	if err1 != nil {
		fmt.Println("err:", err1.Error())
		return
	}
	if err2 != nil {
		fmt.Println("err:", err2.Error())
		return
	}

	//读取数据
	bs := make([]byte,1024,1024)

	for {
		n,err := file1.Read(bs)

		if n == 0 || err == io.EOF {
			fmt.Println("复制结束")
			break
		}

		//写出数据
		file2.Write(bs[:n])
	}

	//关闭文件
	file1.Close()
	file2.Close()

}